//
//  LoginViewController.m
//  cocoapodText
//
//  Created by apple on 16/8/10.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ShiPei.h"
#import "GYGPMainController.h"
#import "LoginViewController.h"
#import <Foundation/Foundation.h>

@interface LoginViewController ()
@property(nonatomic,strong)NSString *username;
@property(nonatomic,strong)NSString *userpass;
@property(nonatomic,strong)NSString *loginsubmit;
@end

@implementation LoginViewController

FSLoginView *loginViewTest;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self registerForKeyboardNotifications];
    [self initMainView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //刷新显示（是否记住密码）
    [loginViewTest refreshView];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}


-(void)initMainView{
    CGFloat titleViewH=68;
    CGFloat titleViewW=455;
    CGFloat loginViewW=490;
    CGFloat loginViewH=330;
    //底层View
    UIView *loginAllBGView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    [loginAllBGView setBackgroundColor:[UIColor brownColor]];
    [loginAllBGView setUserInteractionEnabled:YES];
    [self.view addSubview:loginAllBGView];
    //大背景图
    UIImageView *loginBGImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    [loginBGImageView setImage:[UIImage imageNamed:@"fs_login_bg.png"]];
    [loginAllBGView addSubview:loginBGImageView];
    //标题
    UIImageView *loginTitleImageView=[[UIImageView alloc]initWithFrame:CGRectMake((kScreenW-[ShiPei CGFloatMakeScale:titleViewW])/2, (kScreenH-[ShiPei CGFloatMakeScale:loginViewH])/2-15-[ShiPei CGFloatMakeScale:titleViewH], [ShiPei CGFloatMakeScale:titleViewW], [ShiPei CGFloatMakeScale:titleViewH])];
    [loginTitleImageView setImage:[UIImage imageNamed:@"fs_login_title.png"]];
    [self.view addSubview:loginTitleImageView];
    //loginView
    loginViewTest=[[FSLoginView alloc]initWithFrame:CGRectMake((kScreenW-[ShiPei CGFloatMakeScale:loginViewW])/2, (kScreenH-[ShiPei CGFloatMakeScale:loginViewH])/2, [ShiPei CGFloatMakeScale:loginViewW], [ShiPei CGFloatMakeScale:loginViewH])];
    loginViewTest.delegate=self;
    [loginViewTest.loginIdView setDelegate:self];
    [loginViewTest.loginPassView setDelegate:self];
    
    [self.view addSubview:loginViewTest];
}

-(void)onLogin:(FSLoginView *)loginButton{
    NSString *username=loginButton.loginIdView.text;
    NSString *password=loginButton.loginPassView.text;
    if (![username isEqualToString:@""]&&![password isEqualToString:@""]) {
        _username=username;
        _userpass=password;
        UserLogin *loginmanager=[UserLogin alloc];
        [loginmanager setDelegate:self];
        [loginmanager fsgy_api_user_login_withName:username Pass:password];
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _loginsubmit=@"1";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self timerFired];
        });
    }else if([username isEqualToString:@""]){
        [CommonTool showAllTextDialogWithText:@"用户名为空" parentView:self.view];
    }else if([password isEqualToString:@""]){
        if ([password length]<4) {
            [CommonTool showAllTextDialogWithText:@"密码至少4位" parentView:self.view];
        }else{
            [CommonTool showAllTextDialogWithText:@"密码为空" parentView:self.view];
        }
    }
}


-(void)timerFired{
    if ([_loginsubmit isEqualToString:@"1"]) {
        _loginsubmit=@"0";
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [CommonTool showAllTextDialogWithText:@"服务器异常" parentView:self.view];
    }
}

-(void)onLogin:(UserLogin *)manager result:(NSDictionary *)result{
    if ([_loginsubmit isEqualToString:@"1"]) {
        _loginsubmit=@"0";
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }
    [CommonTool updateValueWithKey:@"username" value:_username];
    NSString *logonCode=[result objectForKey:@"logonCode"];
    if ([logonCode isEqualToString:@"0"]) {
        if (is_save){
            //记住密码
            [CommonTool updateValueWithKey:@"userpass" value:_userpass];
        }else{
            //删除密码
            [CommonTool updateValueWithKey:@"userpass" value:@""];
        }
        //登录成功
        [CommonTool updateValueWithKey:@"is_login" value:@"1"];
        GYGPMainController *gpdock=[[GYGPMainController alloc]init];
        [self presentViewController:gpdock animated:NO completion:nil];
    }else if ([logonCode isEqualToString:@"1"]){
        //用户名或密码错误
        [CommonTool showAllTextDialogWithText:@"用户名或密码错误" parentView:self.view];
    }
}

-(void)onLogout:(UserLogin *)manager result:(NSDictionary *)result{
    NSString *logonCode=[result objectForKey:@"logonCode"];
    if ([logonCode isEqualToString:@"2"]){
        //注销成功
    }else if ([logonCode isEqualToString:@"1"]){
        //用户名或密码错误
    }
}

BOOL is_save=YES;

-(void)onSwitchSavePass:(FSLoginView *)switchSavePassView{
    is_save=!is_save;
    if (is_save) {
        [CommonTool updateValueWithKey:@"is_save_pass" value:@"1"];
        [switchSavePassView.switchSavePassImageView setImage:[UIImage imageNamed:@"login_check_box_1.png"]];
    }else{
        [CommonTool updateValueWithKey:@"is_save_pass" value:@"0"];
        [switchSavePassView.switchSavePassImageView setImage:[UIImage imageNamed:@"login_check_box_0.png"]];
    }
}

-(void)onForget:(FSLoginView *)loginButton{
    
}
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField{
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
//当用户按下return键
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    if (textField==loginViewTest.loginPassView) {
        //限制输入长度
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }else if (textField.text.length >= 16) {
            textField.text = [textField.text substringToIndex:16];
            [CommonTool showAllTextDialogWithText:@"最大长度16位" parentView:loginViewTest];
            return NO;
        }
    }
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

- (void) registerForKeyboardNotifications{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
}

-(void)keyBoardChange:(NSNotification *)notification{
    NSDictionary *dict = notification.userInfo;
    NSValue *aValue = [dict objectForKey:UIKeyboardFrameEndUserInfoKey];
    [UIView animateWithDuration:0.01f animations:^{
        CGRect keyboardRect = [aValue CGRectValue];
        CGRect frame = self.view.frame;
        CGFloat keyboardH=CGRectGetMinY(keyboardRect) - CGRectGetHeight(frame);
        CGFloat bottom=self.view.frame.size.height-loginViewTest.frame.origin.y-[ShiPei CGFloatMakeScale:130]-loginViewTest.loginIdView.frame.size.height;
        if (bottom<(0-keyboardH)) {
            frame.origin.y = bottom+keyboardH;
        }
        self.view.frame = frame;
    }];
}

@end
